#!/usr/bin/python3
import hashlib
import hmac
import base64
import requests
import urllib.parse
import argparse

# CloudStack API相关信息
api_url = "http://10.219.86.140:8080/client/api"
api_key = "IQPQj5cXD_Tswxo_L3bAs6iwWcaoJ5QNDzulpQ19Sj-gnlZL1J6KGPl02a5eZlBTXOHThdguHR0sLwPn1qv9Qw"
secret_key = "VTgEoH4-0Y2Lm2HJBss-dF-OojUQ5Q9lnHDsZ4WzuBzqWXDUi9v-ztEnHX_t9enr8u6Ubm1ajElxqF_IT3YlAQ"
instance_id = "<instance-id>"


def generate_signature(params, secret_key):
    sorted_params = sorted(params.items())
    query_string = '&'.join(['='.join([k, urllib.parse.quote_plus(str(v))]) for k, v in sorted_params])
    signature = hmac.new(secret_key.encode('utf-8'), query_string.lower().encode('utf-8'), hashlib.sha1)
    signature = base64.b64encode(signature.digest())
    return signature.decode('utf-8')


def make_request(command, params):
    params['command'] = command
    params['apikey'] = api_key
    params['response'] = 'json'
    params['signature'] = generate_signature(params, secret_key)
    response = requests.get(api_url, params=params)
    return response.json()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='处理命令行参数')
    parser.add_argument('--url', default=api_url, type=str, help='ACS的api地址')
    parser.add_argument('--ak', default=api_key, type=str, help='AK')
    parser.add_argument('--sk', default=secret_key, type=str, help='sK')
    parser.add_argument('--instanceId', required=True, type=str, help='实例ID')
    args = parser.parse_args()
    api_url = args.url
    api_key = args.ak
    secret_key = args.sk
    instance_id = args.instanceId
    # print(api_url, api_key, secret_key, instance_id)
    params = {
        "id": instance_id
    }
    response = make_request("startVirtualMachine", params)
    print(response)
